package com.hxd.otc.module.coin_deal.fragment;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.LazyFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.CoinDealBottomDialog;
import com.hxd.otc.module.coin_deal.activity.CoinDealListActivity;
import com.hxd.otc.module.coin_deal.activity.MyEntryOrdersActivity;
import com.hxd.otc.module.coin_deal.adapter.ChooseCoinAdapter;
import com.hxd.otc.module.coin_deal.adapter.ChooseTwoCoinAdapter;
import com.hxd.otc.module.coin_deal.adapter.CoinAdapter;
import com.hxd.otc.module.coin_deal.bean.ChooseCoinBean;
import com.hxd.otc.module.coin_deal.bean.CoinBottomDialogBean;
import com.hxd.otc.module.coin_deal.bean.CoinDealRequestBean;
import com.hxd.otc.module.coin_deal.bean.CoinDealResultBean;
import com.hxd.otc.module.coin_deal.bean.CoinRequestTransBean;
import com.hxd.otc.module.coin_deal.contract.CoinDealContract;
import com.hxd.otc.module.coin_deal.presenter.CoinDealPresenter;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.widget.DealTitleBar;
import com.hxd.otc.widget.WalletDialogTipsUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/7/9 11:48
 * 描  述 :  ${币币交易fragment}
 */
public class CoinFragment extends LazyFragment<CoinDealPresenter> implements CoinDealContract.View {

    @BindView(R.id.title_bar)
    DealTitleBar mTitleBar;

    @BindView(R.id.make_tv)
    TextView mMakeText;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.rc_coin)
    RecyclerView rcCoin;

    @BindView(R.id.rc_coin_two)
    RecyclerView rcCoinTwo;

    @BindView(R.id.ll_choose)
    LinearLayout llChoose;

    View errorView;

    View notDataView;

    TextView tvRefresh;

    private boolean isRefresh;
    // mCheckTeamPosition： 被选中的pos, mTwoPos: 第二个adapter pos , mOnePos: 第一个adapter 被选中的pos
    private int mCheckTeamPosition, mTwoPos, mOnePos;

    private CoinDealRequestBean mRequestBean;

    CoinAdapter adapter;
    ChooseCoinAdapter chooseCoinAdapter;
    ChooseTwoCoinAdapter chooseTwoAdapter;

    private CoinDealBottomDialog mBottomBuyDialog;

    List<ChooseCoinBean> coinTypesPrices;

    boolean isFirst = true;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_coin;
    }

    @Override
    protected void initData() {
        mRequestBean = new CoinDealRequestBean();
        //获取最新成交价
        mRefreshLayout.autoRefresh(0, 10, 1);
    }

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        rcCoin.setLayoutManager(new LinearLayoutManager(mContext));
        rcCoinTwo.setLayoutManager(new LinearLayoutManager(mContext));
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });

        notDataView = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) recyclerView.getParent(), false);
        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) recyclerView.getParent(), false);
        tvRefresh = errorView.findViewById(R.id.tv_refresh);
        tvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshLayout.autoRefresh(0, 10, 1);
            }
        });

        initAdapter();

        initChooseAdapter();

        initChooseTwoAdapter();

        mTitleBar.setOnCheckTitleListener(new DealTitleBar.OnCheckTitleListener() {
            @Override
            public void onCheckChanged(boolean isCheck) {
                if (coinTypesPrices == null) {
                    mPresenter.getCoinTypePrice();
                }
                llChoose.setVisibility(isCheck ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onRightClick(View v) {

            }

        });
    }

    /**
     * 设置titile,并根据title 去查询 该币种对应的数据
     *
     * @param str
     */
    public void setTitle(String str) {
        mTitleBar.setQueuesContent(str);
        if (!isFirst) {
            isFirst = true;
            refreshData();
        }
    }

    private void refreshData() {
        isRefresh = true;
        mRequestBean.pageNo = Constant.PAGE_DEFAULT;
//        mPresenter.getLastPrice(mTitleBar.getQueuesContent());
        mRequestBean.bbTransPair = mTitleBar.getQueuesContent();
        mPresenter.getCoinTypePrice();
        mPresenter.loadData(mRequestBean);
    }

    private void loadMoreData() {
        isRefresh = false;
        mRequestBean.pageNo++;
        mRequestBean.bbTransPair = mTitleBar.getQueuesContent();
        mPresenter.loadData(mRequestBean);
    }

    private void initAdapter() {
        if (adapter == null) {
            adapter = new CoinAdapter();
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (!UserHelper.isSetPayPassword()) {
                        WalletDialogTipsUtil.showTpwTipsDialog(getActivity());
                        return;
                    }
                    initCoinDialogBean((CoinDealResultBean.DataBean) adapter.getData().get(position));
                }
            });
        }
        recyclerView.setAdapter(adapter);
    }

    private void initChooseAdapter() {
        if (chooseCoinAdapter == null) {
            chooseCoinAdapter = new ChooseCoinAdapter();
            chooseCoinAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    mOnePos = position;
                    chooseCoinAdapter.setSelectPos(position);
                    chooseTwoAdapter.setSelectPos(-1);
                    chooseTwoAdapter.setNewData(coinTypesPrices.get(position).priceVoList);
                }
            });
        }
        rcCoin.setAdapter(chooseCoinAdapter);
    }


    private void initChooseTwoAdapter() {
        if (chooseTwoAdapter == null) {
            chooseTwoAdapter = new ChooseTwoCoinAdapter();
            chooseTwoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    chooseTwoAdapter.setSelectPos(position);
                    mTwoPos = position;
                    mCheckTeamPosition = mOnePos;
                    mTitleBar.setDealData(((ChooseCoinBean.DataBean) adapter.getData().get(position)).transPair, false);
                    llChoose.setVisibility(View.GONE);
                    refreshData();
                    if (Double.valueOf(((ChooseCoinBean.DataBean) adapter.getData().get(position)).price) <= 0) {
                        mMakeText.setText(R.string.new_deal);
                    } else {
                        mMakeText.setText(getString(R.string.last_price_aec,
                                StringUtil.format4Number(Double.valueOf(((ChooseCoinBean.DataBean) adapter.getData().get(position)).price)),
                                coinTypesPrices.get(mCheckTeamPosition).coinType));
                    }
                }
            });
        }
        rcCoinTwo.setAdapter(chooseTwoAdapter);
    }

    /**
     * 交易买入卖出
     *
     * @param bbAdvertId
     * @param dealCount
     * @param password
     */
    private void transCoinDeal(String bbAdvertId, String dealCount, String password) {
        CoinRequestTransBean bean = new CoinRequestTransBean();
        bean.bbAdvertId = bbAdvertId;
        bean.transAmount = dealCount;
        bean.password = password;
        mPresenter.transCoinDeal(bean);
    }

    String strId;

    private void initCoinDialogBean(final CoinDealResultBean.DataBean bean) {
        CoinBottomDialogBean bottomBean = new CoinBottomDialogBean();
        bottomBean.maxCount = bean.restAmount;
        bottomBean.money = bean.price;
        bottomBean.typeDeal = 1;
        strId = bean.getId();
        if (TextUtils.isEmpty(mTitleBar.getQueuesContent())) {
            return;
        }
        String[] splitstr = mTitleBar.getQueuesContent().split("/");
        bottomBean.moneyUnit = splitstr[1];
        bottomBean.numberUnit = splitstr[0];
        bottomBean.price = getString(R.string.price_s_aec, String.valueOf(bean.price), splitstr[1]);
        bottomBean.count = getString(R.string.count_s_msc, StringUtil.formatNumber(bean.restAmount, 4, false), splitstr[0]);
        bottomBean.title = getString(R.string.buy_msc, splitstr[0]);
        if (mBottomBuyDialog == null) {
            mBottomBuyDialog = new CoinDealBottomDialog(getContext(), bottomBean);
            mBottomBuyDialog.setOnItemClickListener(new CoinDealBottomDialog.OnItemClickListener() {
                @Override
                public void onSure(View v, String dealCount, String password) {
                    transCoinDeal(strId, dealCount, password);
                }
            });
        } else {
            mBottomBuyDialog.setData(bottomBean);
        }
        mBottomBuyDialog.show();

    }

    @Override
    protected void initEvent() {


    }


    @Override
    protected CoinDealPresenter createPresenter() {
        return new CoinDealPresenter(this);
    }


    @Override
    public void resultData(List<CoinDealResultBean.DataBean> list) {
        if (isRefresh) {
            mRefreshLayout.setEnableLoadMore(true);
            if (list != null && list.size() <= 0) {
                adapter.setEmptyView(notDataView);
            }
            adapter.setNewData(list);
        } else {
            if (list == null || list.size() < mRequestBean.pageSize) {
                mRefreshLayout.setEnableLoadMore(false);
            } else {
                mRefreshLayout.setEnableLoadMore(true);
                adapter.addData(list);
            }
        }
    }

    @Override
    public void resultLastPrice(String lastPrice) {
        if (lastPrice == null || TextUtils.isEmpty(lastPrice.trim())) {
            mMakeText.setText(getString(R.string.new_deal));
        } else {
            if (TextUtils.isEmpty(mTitleBar.getQueuesContent())) {
                return;
            }
            String[] splitstr = mTitleBar.getQueuesContent().split("/");
            mMakeText.setText(getString(R.string.last_price_aec, StringUtil.format4Number(Double.valueOf(lastPrice)), splitstr[0]));
        }

    }

    @Override
    public void getCoinTypePrice(List<ChooseCoinBean> coins) {
        coinTypesPrices = coins;
        chooseCoinAdapter.setNewData(coins);
        if (coins.size() > 0) {
            if (isFirst) {//匹配title 中的数据， 遍历集合，并通知adapter选中
                isFirst = false;
                for (int i = 0; i < coins.size(); i++) {
                    for (int j = 0; j < coins.get(i).priceVoList.size(); j++) {
                        if (coins.get(i).priceVoList.get(j).transPair.equals(mTitleBar.getQueuesContent())) {
                            mTwoPos = j;
                            mOnePos = i;
                            mCheckTeamPosition = mOnePos;
                            break;
                        }
                    }
                }
                chooseTwoAdapter.setNewData(coins.get(mCheckTeamPosition).priceVoList);
                chooseCoinAdapter.setSelectPos(mCheckTeamPosition);
                chooseTwoAdapter.setSelectPos(mTwoPos);
            }

            if (Double.valueOf(coins.get(mCheckTeamPosition).priceVoList.get(mTwoPos).price) <= 0) {
                mMakeText.setText(R.string.new_deal);
            } else {
                mMakeText.setText(getString(R.string.last_price_aec,
                        StringUtil.format4Number(Double.valueOf(coins.get(mCheckTeamPosition).priceVoList.get(mTwoPos).price)), coins.get(mCheckTeamPosition).coinType));
            }
        }
    }

    @Override
    public void deleteCoinDealSucceed() {
        refreshData();
    }

    @Override
    public void transCoinDealSucceed() {
        refreshData();
        $startActivity(CoinDealListActivity.class);
    }

    @Override
    public void onShowNoMore() {
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadMore();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.Deal.REQUEST_MY_ENTRY_ORDERS_CODE:
                    refreshData();
                    break;
            }
        }
    }

    @OnClick({R.id.convert_tv, R.id.status_tv, R.id.ll_choose, R.id.view})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.convert_tv:
                if (UserHelper.isLogin()) {
                    $startActivityForResult(MyEntryOrdersActivity.class, Constant.Deal.REQUEST_MY_ENTRY_ORDERS_CODE);
                } else {
                    $startActivity(LoginActivity.class);
                }
                break;
            case R.id.status_tv:
                if (UserHelper.isLogin()) {
                    $startActivity(CoinDealListActivity.class);
                } else {
                    $startActivity(LoginActivity.class);
                }
                break;
            case R.id.ll_choose:
                llChoose.setVisibility(View.VISIBLE);
                break;
            case R.id.view:
                mTitleBar.setCheck(false);
                llChoose.setVisibility(View.GONE);
                break;
        }
    }

}
